package com.dj.mingkong.portal.biz.service.music.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.common.constant.RedisConstants;
import com.dj.mingkong.common.exception.ValidateException;
import com.dj.mingkong.common.infrastructure.eo.database.music.BoxEo;
import com.dj.mingkong.common.infrastructure.eo.database.music.BoxLikeEo;
import com.dj.mingkong.common.microservice.UserContext;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.portal.biz.controller.music.vo.request.BoxLikeAddVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.BoxLikeQueryVo;
import com.dj.mingkong.portal.biz.controller.music.vo.response.BoxLikeVo;
import com.dj.mingkong.portal.biz.repository.database.music.BoxLikeRepository;
import com.dj.mingkong.portal.biz.repository.database.music.BoxRepository;
import com.dj.mingkong.portal.biz.service.music.BoxLikeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * 音乐盒点赞管理
 *
 * @author zenglonghui
 * @date: 2023/3/23 17:07
 */
@Slf4j
@Service("boxLikeService")
public class BoxLikeServiceImpl implements BoxLikeService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private BoxRepository boxRepository;
    @Resource
    private BoxLikeRepository boxLikeRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BoxLikeAddVo addVo) {
        final String key = RedisConstants.BOX_LIKE.concat(UserContext.getUserId().toString())
                .concat(RedisConstants.KEY_SPLIT).concat(addVo.getBoxId().toString());
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            throw new ValidateException("24小时内不允许重复点赞！");
        }
        final BoxEo boxEo = boxRepository.getById(addVo.getBoxId());
        AssertUtils.isNotNull(boxEo, "boxId invalid");
        final BoxLikeEo boxLikeEo = BoxLikeEo.builder()
                .userId(UserContext.getUserId())
                .boxId(addVo.getBoxId())
                .build();
        boxLikeRepository.save(boxLikeEo);
        boxRepository.updateById(boxEo.setLikeCount(boxEo.getLikeCount() + 1));
        redisTemplate.opsForValue().set(key, RedisConstants.BOX_LIKE, 1, TimeUnit.DAYS);
    }

    @Override
    public Page<BoxLikeVo> pageByVo(BoxLikeQueryVo queryVo) {
        return boxLikeRepository.getMapper().listPage(Page.of(queryVo.getPage(), queryVo.getPageSize()), queryVo);
    }
}
